#!/usr/bin/env bash

set -o errexit -o pipefail -o noclobber -o nounset

OPTIONS=h
LONGOPTS=help,gpghome:,hostname:,keytype:

! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")

if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
  # e.g. return value is 1
  #  then getopt has complained about wrong arguments to stdout
  exit 2
fi

eval set -- "$PARSED"

FINAL_GNUPGHOME=/root/.gnupg
HOSTNAME=$(hostname)
KEYTYPE="RSA"

usage() {
    echo "$0: [--hostname hostname] [--gpghome home] [--keytype keytype]"
    echo
    echo "  keytype: RSA (default) or Curve25519"
    echo
}

while true; do
  case "$1" in
    -h|--help)
      usage
      exit 0
      ;;
    --gpghome)
      FINAL_GNUPGHOME=$2
      shift 2
      ;;
    --hostname)
      HOSTNAME=$2
      shift 2
      ;;
    --keytype)
      KEYTYPE=$2
      shift 2
      ;;
    --)
      shift
      break
      ;;
    *)
      echo "unknown option: $1"
      usage
      exit 3
      ;;
  esac
done

if [[ -e "$FINAL_GNUPGHOME" ]]; then
  echo "secret path ${FINAL_GNUPGHOME} already exists"
  exit 1
fi

export GNUPGHOME=$(mktemp -d)
trap "rm -rf $GNUPGHOME" EXIT


cat > "$GNUPGHOME/key-template" <<EOF
%no-protection
EOF

if [[ "$KEYTYPE" == "Curve25519" ]]; then
  cat >> "$GNUPGHOME/key-template" <<EOF
Key-Type: eddsa
Key-Curve: Ed25519
Key-Usage: sign
Subkey-Type: ecdh
Subkey-Curve: Curve25519
Subkey-Usage: encrypt
EOF
elif [[ "$KEYTYPE" == "RSA" ]]; then
  cat >> "$GNUPGHOME/key-template" <<EOF
Key-Type: 1
Key-Length: 2048
EOF
else
  echo "unknown keytype '$KEYTYPE'"
  exit 1
fi

cat >> "$GNUPGHOME/key-template" <<EOF
Name-Real: $HOSTNAME
Name-Email: root@$HOSTNAME
Expire-Date: 0
EOF

gpg --quiet --batch --gen-key "${GNUPGHOME}/key-template"
echo >&2 "You can use the following command to save it to a file:"
echo >&2 "cat > $HOSTNAME.asc <<EOF"
gpg --export --armor >&2
echo >&2 'EOF'

fpr=$(gpg --quiet --list-keys --with-colons --fingerprint | awk -F: '$1 == "fpr" { print $10;}')
echo >&2 "fingerprint: $fpr"

rm "${GNUPGHOME}/key-template"
parent=$(dirname "$FINAL_GNUPGHOME")
mkdir -p "$parent"
mv "$GNUPGHOME" "$FINAL_GNUPGHOME"
